package com.wbc.utils;


import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;

/**
 * @author wangbingchen
 * @Description
 * @create 2021-12-03 14:01
 */

public class ReadTextUtil {


    private ReadTextUtil(){}
    /**
     * 读取本地 txt文件的内容
     * @param file 想要读取的文件对象
     * @return 返回 list<String> 每一个String 为一行数据
     */
    public static List<String> readText(File file){
        List<String> list = new ArrayList<String>();

//        String result = "";
        try{
            BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
            String s = null;
            while(isEmpty(s = br.readLine())){//使用readLine方法，一次读一行
                list.add(s);
//                result = result + "\n" +s;
            }
            br.close();
        }catch(Exception e){
            e.printStackTrace();
        }
        return list;
    }

    private static boolean isEmpty(String str) {
        return str!=null&&!"".equals(str);
    }

    //读取网络文件
    public static List<String> readText(String host){
        List<String> list = new ArrayList<String>();
        String str = "";
        URL url = null;
        try {
            url = new URL(host);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            InputStreamReader isr = new InputStreamReader(connection.getInputStream());
            BufferedReader br = new BufferedReader(isr);
            while (isEmpty(str = br.readLine())) {
                list.add(str);
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

}

